package com.zrrd.binarysearch;

public class BinarySearch {
    public int binarySearch(int[] array, int temp) {
        int start = 0;
        int end = array.length - 1;
        int middle;
        while (start <= end) {
            middle = (start + end) / 2;
            if (temp < array[middle]) {
                end = middle - 1;
            } else if (temp > array[middle]) {
                start = middle + 1;
            } else {
                return middle;
            }
        }
        return -start - 1;
    }

    public int binarySearch(int[] array, int temp, int start, int end) {
        if (start > end) {
            return -start - 1;
        }
        int middle = (start + end) / 2;
        if (temp < array[middle]) {
            return binarySearch(array, temp, start, middle - 1);
        } else if (temp > array[middle]) {
            return binarySearch(array, temp, middle + 1, end);
        } else {
            return middle;
        }
    }

    public static void main(String[] args) {
        BinarySearch binarySearch = new BinarySearch();
        int[] array = new int[]{2, 11, 15, 23, 27, 45, 49};
        System.out.println(binarySearch.binarySearch(array, 0, 0, array.length));
    }
}
